package com.zoo.sys.realm;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zoo.sys.entity.Permission;
import com.zoo.sys.entity.User;
import com.zoo.sys.mapper.PermissionMapper;
import com.zoo.sys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: WangB
 * @Date: 2022/3/22
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("loginname", username);
        User user = userMapper.selectOne(qw);
        if (ObjectUtil.isEmpty(user)) {
            throw new BadCredentialsException("输入的账户不存在！");
        }

        List<GrantedAuthority> authorities = permissionMapper.selectPermissionByUid(user.getId())
                .stream().map(m -> m.getPercode()).filter(s -> StrUtil.isNotEmpty(s)).collect(Collectors.toSet())
                .stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList());

        return  new JwtUser(user,authorities);
    }
}
